class Solution {
public:
    int maxProfit(int k, vector<int>& prices) {
        int n = prices.size();
        k = min(k, n / 2);
        vector<vector<int>> f(n, vector<int>(k + 1, -0x3f3f3f3f));
        vector<vector<int>> g(n, vector<int>(k + 1, -0x3f3f3f3f));
        
        f[0][0] = 0;
        g[0][0] = -prices[0];
        
        for (int i = 1; i < n; ++i)
        {
            for (int j = 0; j < k + 1; ++j)
            {
                if (j == 0)
                    f[i][j] = f[i - 1][j];
                else
                    f[i][j] = max(f[i - 1][j], g[i - 1][j - 1] + prices[i]);
                    
                g[i][j] = max(g[i - 1][j], f[i - 1][j] - prices[i]);
            }
        }
        
        int ret = f[n - 1][0];
        for (auto i : f[n - 1])
        {
            if (i > ret)
                ret = i;
        }
        
        return ret;
    }
};
